class ConversationsController < ApplicationController
  before_filter :login_required, :authorization_required, :find_customer
  
  # GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
  verify :method => :post, :only => [ :create ], :redirect_to => { :action => :index }
  verify :method => :put, :only => [ :update ], :redirect_to => { :action => :index }
  verify :method => :delete, :only => [ :destroy, :destroy_selected ], :redirect_to => { :action => :index }
  
  def index
    if(@customer.nil?)
      @conversations = Conversation.find(:all, :order => 'contacted_on desc, created_on desc')
    else
      @conversations = @customer.conversations
    end
    respond_to do |format|
      format.html {render :action => 'list.rhtml'}
      format.js {render :action => 'list.rjs'}
      format.xml {render :xml => @conversations.to_xml}
    end
  end
  
  def show
    @conversation = Conversation.find(params[:id])
  end  
  
  def new
    @conversation = Conversation.new
    respond_to do |format|
      format.html {render :action => 'new.rhtml'}
      format.js {render :action => 'new.rjs'}
    end
  end
  
  def create
    conversation = Conversation.new(params[:conversation])
    conversation.user_id = current_user.id
    @customer.conversations << conversation
    @conversations = @customer.conversations
    if @customer.save
      redirect_to :controller => 'customers', :action => 'show', :id => @customer unless request.xhr?
    else
      render :action => 'new' unless request.xhr?
    end
  end
  
  def edit
    @conversation = Conversation.find(params[:id])
    @customer = @conversation.customer
    respond_to do |format|
      format.html {render :action => 'edit.rhtml'}
      format.js {render :action => 'edit.rjs'}
    end
  end
  
  def update
    @conversation = Conversation.find(params[:id])
    @conversations = @conversation.customer.conversations
    if @conversation.update_attributes(params[:conversation])
      redirect_to :controller => 'customers', :action => 'show', :id => @customer unless request.xhr?
    else
      render :action => 'edit' unless request.xhr?
    end
  end
  
  def destroy
    Conversation.find(params[:id]).destroy
    index
  end
  
  def destroy_selected
    @conversations = @customer.conversations
    unless params[:selected].nil?
      params[:selected].each do |id|
        conversation = Conversation.find(id)
        @customer = conversation.customer
        conversation.destroy
      end
    end
    redirect_to :controller => 'customers', :action => 'show', :id => @customer unless request.xhr?
  end
end